import express from "express";
import cors from "cors"
import bodyParser from 'body-parser'
import mysql from 'mysql'
import path from "path"
import { v4 as uuidv4 } from 'uuid';
import jwt from 'jsonwebtoken'

// 导入自定义包
import { writeImg, writeAudio } from './myPackage/writeBase64File.js'
import { getStat } from './myPackage/pathManage.js'


// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })
const app = express()

app.use("/statics", express.static("statics"))
app.use(cors())
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb' }));

// 解码

// 数据库配置
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'voiceLetter'
});

connection.connect();






app.get('/', (req, res) => {
    console.log(req.query)
    res.send(`我是一个数据`)

})

// 添加信集合箱
app.post('/api/add/cover', urlencodedParser, (req, res) => {
    const updataData = req.body.updataData
    // 1.校验
    //      1.1判断用户账户是否正确



    //      1.2循环判断是否为空
    for (let val in updataData) {
        if (updataData[val] == "") {
            res.status(500)
            console.log("/api/add/cover请求失败")
            return res.send("请求失败")
        }
    }


    // 用户提交的数据
    //      封面数据
    let userId = updataData.userId
    let coverId = updataData.coverId// 用户封面ID
    let title = updataData.title
    let coverScript = updataData.coverScript.replace(/\n/g, '<br/>') //将换行符替换成html标签以保存数据库
    let toPeople = updataData.toPeople
    let fromPeople = updataData.fromPeople
    let enterScript = updataData.enterScript
    let enterPassword = updataData.enterPassword
    var imgData = updataData.coverImg[0].url//图片base64数据
    const date = new Date();
    let dateNow = date.toLocaleDateString() + "  " + date.getHours() + "时"

    // 2.将封面图片保存
    let basePath = './statics/img'
    basePath = path.join(basePath, coverId)
    let FileFullPath = path.join(basePath, 'coverImg.png')// 文件完整路径
    getStat(basePath).then(function () { // 创建目录
        writeImg(imgData, FileFullPath)// 写入图片文件
    })
    // 3.写入数据库
    new Promise(function (resolve, reject) {
        //  判断封面是否已经存在
        let findSql = "SELECT * FROM voiceLetter.lettercover WHERE lettercover.coverId = ?"
        connection.query(findSql, coverId, (err, results) => {
            if (err) return console.log("查询失败", err.message)
            if (results[0]) { res.status(500); res.send("已存在") }
            console.log("coverfind", results)
            if (results == '') {
                resolve()
            }
        })
    }).then(() => {
        // 为空时保存封面数据到数据库
        let addCoverSql = "INSERT INTO `voiceLetter`.`lettercover` (`coverId`, `coverScript`, `toPeople`, `fromPeople`, `enterPassword`,`coverImg`, `userId`, `enterScript`, `title`, `date`) VALUES (?, ?, ?, ?, ?, ? ,? ,? ,? ,?)"
        connection.query(addCoverSql, [coverId, coverScript, toPeople, fromPeople, enterPassword, FileFullPath, userId, enterScript, title, dateNow], (error, results) => {
            if (error) return console.log("封面数据写入失败", error.message)
            console.log('保存到封面')
            res.send("保存成功")
        })

    })

})







//添加信件
app.post('/api/add/letter', urlencodedParser, (req, res) => {
    // 1.校验
    //判断用户账户是否正确



    //      循环判断是否为空
    for (let val in req.body.updataData) {
        if (req.body.updataData[val] == "" && val != "voiceBackgroundMp3" && val != "coverId") {
            res.status(500)
            return res.send("请求失败")
        }
    }

    const updataData = req.body.updataData
    //      用户提交的数据
    //      封面数据
    let user = JSON.parse(req.body.loginData).user
    let coverId = updataData.coverId// 用户封面ID
    //      单信部分数据
    const letterUuid = uuidv4()
    let paperText = updataData.paperText.replace(/\n/g, '<br/>') //将换行符替换成html标签以保存数据库
    let postMothods = updataData.postMothods.join(",") //转换为字符串
    var bVoiceData = updataData.voiceBackgroundMp3[0] ? updataData.voiceBackgroundMp3[0].url : null;//背景音乐base64数据
    var lVoiceData = updataData.letterVoice[0] ? updataData.letterVoice[0].url : null;
    let title = updataData.title
    const date = new Date()
    let dateNow = date.toLocaleDateString() + "  " + date.getHours() + "时"

    let singelLetterPath = 'voiceLetterSingle'


    //  1.1判断该用户下是否有该coverid（待敲）


    // 2.将背景音乐文件保存
    let baseVoicePath = './statics/voice'
    if (coverId) baseVoicePath = path.join(baseVoicePath, coverId)
    getStat(baseVoicePath).then(function () { // 创建音乐文件一级目录
        baseVoicePath = path.join(baseVoicePath, letterUuid)
        return getStat(baseVoicePath)// 创建音乐文件二级每封信的音频管理目录
    }).then(function () {
        let backgroundVoiceFullPath = null
        let letterVoiceFullPath = null
        if (bVoiceData) {  //判断有值
            backgroundVoiceFullPath = path.join(baseVoicePath, 'backgroundVoice.mp3')// 文件完整路径
            writeAudio(bVoiceData, backgroundVoiceFullPath)
        }


        // 4.保存语音信件
        //不为空时写入
        if (lVoiceData) {
            letterVoiceFullPath = path.join(baseVoicePath, 'letterVoice.mp3')// 文件完整路径
            writeAudio(lVoiceData, letterVoiceFullPath)
        }


        //  保存信件中的图片
        paperText = paperText.replace(/<img src='/g, `<img src='http://144.48.241.196:8080/${baseVoicePath}/`)
        let imgFiles = updataData.paperTextImg
        for(let imgFile of imgFiles){
            let imgFilePath = path.join(baseVoicePath,imgFile.name)
            let imgFileData = imgFile.url
            console.log(imgFilePath)
            writeImg(imgFileData, imgFilePath)// 写入图片文件
        }

        // 5.将用户提交数据及文件路径保存到数据库

        //      保存信的数据到letter数据表 
        //      判断是否有coverId
        console.log("coverID:",coverId)
        if (coverId) {
            let addLetterSql = "INSERT INTO `voiceLetter`.`lettersmanage` (`postMothods`, `paperText`, `backgroundVoice`, `letterVoice`, `coverId`, `user`, `title`, `date`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
            connection.query(addLetterSql, [postMothods, paperText, backgroundVoiceFullPath, letterVoiceFullPath, coverId, user, title, dateNow], (error, results) => {
                if (error) return console.log(error.message)
                console.log('保存信件成功')
                res.send("保存11成功")
            })
        }else{
            let addLetterSql = "INSERT INTO `voiceLetter`.`lettersingle` (`postMothods`, `paperText`, `backgroundVoice`, `letterVoice`, `user`, `title`, `date`) VALUES (?, ?, ?, ?, ?, ?, ?)"
            connection.query(addLetterSql, [postMothods, paperText, backgroundVoiceFullPath, letterVoiceFullPath, user, title, dateNow], (error, results) => {
                if (error) return console.log(error.message)
                console.log('保存信件成功')
                res.send("保存11成功")
            })
        }




    })

})

// 匹配信封
app.post('/cover/find', urlencodedParser, (req, res) => {
    let coverId = req.body.coverId
    let findCoverSql = "SELECT * from voiceLetter.lettercover WHERE lettercover.coverId = ?;"
    connection.query(findCoverSql, coverId, (err, results) => {
        if (err) return console.log("findcover", err.message)
        console.log(results)
        if (!results[0]) {
            //没有该信件
            res.status(404)
            return res.send("查询失败")
        }
        //有信件的情况下匹配密码是否正确
        if (req.body.enterPassword != results[0].enterPassword) {
            //不正确
            results[0].enterPassword = ""
            res.statusMessage = "enter"
            res.send(results[0])
        } else {
            // 密码正确，返回信的数据
            let findLetterSql = "SELECT * FROM voiceLetter.lettersmanage WHERE coverId = ?"
            connection.query(findLetterSql, coverId, (err, results) => {
                if (err) return console.log("findletter失败", err.message)
                res.statusMessage = "letters"
                res.send(results)
            })


        }

    })

})


//匹配用户是否存在
app.post('/api/match/user', urlencodedParser, (req, res) => {
    //匹配用户
    const user = req.body.user
    const matchNameSql = "SELECT user from voiceLetter.users WHERE user = ?"
    connection.query(matchNameSql, [user], (err, results) => {
        if (err) return console.log("matchNameSql", err.message)
        res.send(results[0])
    })

})

// 匹配信Id是否存在
app.post('/api/match/coverId', urlencodedParser, (req, res) => {
    const coverId = req.body.coverId
    console.log("查询")
    const findCoverSql = "SELECT coverId FROM voiceLetter.lettercover WHERE coverId = ?"
    connection.query(findCoverSql, coverId, (err, results) => {
        if (err) return console.log("查询信件Id失败", err.message)
        if (results[0]) res.status(220)
        console.log(results)
        res.send(results)
    })
})


//返后用户信息
app.post('/api/match/userData', urlencodedParser, (req, res) => {

    // 1.提取请求信息
    const loginData = JSON.parse(req.body.loginData)
    let user = loginData.user

    //2.验证登录
    new Promise((response, reject) => {

        const matchNameSql = "SELECT `user`, `username` from voiceLetter.users WHERE user=?"
        connection.query(matchNameSql, [user], (err, results) => {
            if (err) return console.log("matchNameSql", err.message)
            response(results[0])
        })

    }).then((response) => {
        console.log(response)
        //3.验证成功，返回用户信息，返回匹配到的信件
        const findCoverSql = "SELECT * from voiceLetter.lettercover WHERE userId = ?"
        connection.query(findCoverSql, user, (err, results) => {
            if (err) return console.log("查找信件失败", err.message)
            res.send({ userData: response, coverData: results })
        })
    })



})




//进行登录
app.post('/api/match/login', urlencodedParser, (req, res) => {
    console.log("登录账户", req.body)
    const matchNameSql = "SELECT * FROM voiceLetter.users WHERE user = ? and password = ?"
    connection.query(matchNameSql, [req.body.user, req.body.password], (err, results) => {
        if (err) return console.log("matchlogin", err.message)
        if (!results[0]) {
            res.status(220)//匹配不到用户
        }

        //加密返回数据
        let secret = 'test001'
        const token = jwt.sign({
            data: results[0]
        }, secret, { expiresIn: '7d' });
        const redata = {
            user: req.body.user,
            token,
        }


        res.send(redata)
    })

})


//注册账户
app.post('/api/register/user', urlencodedParser, (req, res) => {
    console.log("注册账户", req.body)
    const registerNameSql = "INSERT INTO `voiceLetter`.`users` SET ?"
    connection.query(registerNameSql, req.body, (err, results) => {
        if (err) {
            res.status(300)
            res.send(err)
            return console.log("注册账户失败", err.message)
        }
        res.send(results)
    })

})

var server = app.listen(80, function () {
    console.log("开启服务")

})